﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace WindowService
{
    public class Ini  
    {  
        // 声明INI文件的写操作函数 WritePrivateProfileString()  
  
        [System.Runtime.InteropServices.DllImport("kernel32")]  
  
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);  
  
        // 声明INI文件的读操作函数 GetPrivateProfileString()  
  
        [System.Runtime.InteropServices.DllImport("kernel32")]  
  
        private static extern int GetPrivateProfileString(string section, string key, string def, System.Text.StringBuilder retVal, int size, string filePath);

        [System.Runtime.InteropServices.DllImport("kernel32")]  
        private static extern int GetPrivateProfileString(string section, string key, string defVal, Byte[] retVal, int size, string filePath);
  
        private string sPath = null;
        public Ini(string iniDirPath, string iniFileName, string defaultContent)  
        {
            this.sPath = iniDirPath + iniFileName;
            judgeDefaultContent(iniDirPath, sPath, defaultContent);
        }

        private void judgeDefaultContent(string iniDirPath, string iniFilePath, string defaultContent)
        {
            Log.WriteLog("Ini judgeDefaultContent", LogType.Trace);
            StreamWriter writer = null;
            try
            {
                if (!Directory.Exists(iniDirPath))
                {
                    Log.WriteLog("Ini config directory:" + iniDirPath + " is not exist, created", LogType.Trace);
                    Directory.CreateDirectory(iniDirPath);
                }
                if (!File.Exists(iniFilePath))
                {
                    Log.WriteLog("Ini config file:" + iniFilePath + " is not exist, created", LogType.Trace);
                    writer = File.CreateText(iniFilePath);
                    writer.Write(Log.gb2312_utf8(defaultContent));
                    writer.Close();
                }
            }
            catch (Exception e)
            {
                Log.WriteLog("Ini Create config file error: " + e.Message, LogType.Error);
            }
        }  
  
        public void Write(string section, string key, string value)  
        {  
  
            // section=配置节，key=键名，value=键值，path=路径  
  
            WritePrivateProfileString(section, key, value, sPath);  
  
        }  
        public string ReadValue(string section, string key)  
        {  
  
            // 每次从ini中读取多少字节  
  
            System.Text.StringBuilder temp = new System.Text.StringBuilder(255);  
  
            // section=配置节，key=键名，temp=上面，path=路径  
  
            GetPrivateProfileString(section, key, "", temp, 255, sPath);

            Log.WriteLog("Ini Read config [" + section + "] " + key + ": " + temp.ToString(), LogType.Trace);
  
            return temp.ToString();  
  
        }  

        /// <summary>
        /// 读取INI文件
        /// </summary>
        /// <param name="Section">段，格式[]</param>
        /// <param name="Key">键</param>
        /// <returns>返回byte类型的section组或键值组</returns>
        public ArrayList ReadValues(string section, string key)
        {
            byte[] temp = new byte[255];

            GetPrivateProfileString(section, key, "", temp, 255, sPath);
            string tempStr = System.Text.Encoding.Default.GetString(temp);
            string[] tempStrArr = tempStr.Split('\0');
            ArrayList resultStrArr = new ArrayList();
            for (int i = 0; i < tempStrArr.Length; i++)
            {
                if (tempStrArr[i] != "")
                {
                    resultStrArr.Add(tempStrArr[i]);
                }
            }

            return resultStrArr;
        }
        /// <summary>
        /// 读取INI文件的整形值
        /// </summary>
        /// <param name="Section">段，格式[]</param>
        /// <param name="Key">键</param>
        /// <param name="MinValue">最大值</param>
        /// <param name="MaxValue">最小值</param>
        /// <param name="DefaultValue">默认值(0)</param>
        /// <returns>返回int类型的section组key值</returns>
        public int getIntConfig(string section, string key, int minValue, int maxValue, int defaultValue = 0)
        {
            int intValue = defaultValue;
            try
            {
                intValue = int.Parse(ReadValue(section, key));
            }
            catch (Exception e)
            {
                Log.WriteLog("Ini Setting \"[" + section + "]" + key + "\" Error " + e.Message, LogType.Error);
            }
            if (intValue < minValue)
            {
                intValue = minValue;
                Log.WriteLog("Ini Setting \"ProcessPutInterval\" should >= " + minValue.ToString(), LogType.Error);
            }
            if (intValue > maxValue)
            {
                intValue = maxValue;
                Log.WriteLog("Ini Setting \"ProcessPutInterval\" should <= " + maxValue.ToString(), LogType.Error);
            }
            return intValue;
        }
        /// <summary>
        /// 读取INI文件的字符串值
        /// </summary>
        /// <param name="Section">段，格式[]</param>
        /// <param name="Key">键</param>
        /// <param name="DefaultValue">默认值</param>
        /// <returns>返回int类型的section组key值</returns>
        public string getStrConfig(string section, string key, string defaultValue = null)
        {
            string strValue = defaultValue;
            try
            {
                strValue = ReadValue(section, key);
            }
            catch (Exception e)
            {
                Log.WriteLog("Ini Setting \"[" + section + "]" + key + "\" Error " + e.Message, LogType.Error);
            }
            return strValue;
        }
        /// <summary>
        /// 读取INI文件的时间点值
        /// </summary>
        /// <param name="Section">段，格式[]</param>
        /// <param name="Key">键</param>
        /// <param name="DefaultValue">默认值(00:00:00)</param>
        /// <returns>返回int类型的section组key值</returns>
        public string getTimeConfig(string section, string key, string defaultValue = "00:00:00")
        {
            string timeValue = defaultValue;
            try
            {
                timeValue = DateTime.Parse(ReadValue(section, key)).ToString("HH:mm:ss");
            }
            catch (Exception e)
            {
                Log.WriteLog("Ini Setting \"[" + section + "]" + key + "\" Error " + e.Message, LogType.Error);
            }
            return timeValue;
        }
    }
}
